package com.ifacebox.client.tools;

import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import javax.swing.*;
import java.awt.*;
import java.io.File;

/**
 * @author znn
 */
public class FaceImagePerson {
    private File faceFile;
    private ImageIcon faceImage;
    private FacePersonInfo facePersonInfo;

    public FaceImagePerson(File faceFile, FaceLuckDrawConfig faceLuckDrawConfig) {
        this.setFaceFile(faceFile);
        this.setFaceImage(this.toFaceImage(faceLuckDrawConfig.getFaceImageSize()));
        this.setFacePersonInfo(this.toFacePersonInfo(faceLuckDrawConfig.getFacePersonPath()));
    }

    private ImageIcon toFaceImage(Dimension faceSize) {
        ImageIcon faceImage = new ImageIcon(this.faceFile.toURI().getPath());
        faceImage.setImage(faceImage.getImage().getScaledInstance(faceSize.width, faceSize.height, Image.SCALE_SMOOTH));
        return faceImage;
    }

    private FacePersonInfo toFacePersonInfo(File facePersonPath) {
        FacePersonInfo facePersonInfo;
        try {
            String fileName = FilenameUtils.getBaseName(this.faceFile.getName());
            String fileJson = FileUtils.readFileToString(new File(facePersonPath, fileName + ".txt"), "UTF-8");
            facePersonInfo = JSON.parseObject(fileJson, FacePersonInfo.class);
        } catch (Exception e) {
            facePersonInfo = new FacePersonInfo();
        }
        return facePersonInfo == null ? new FacePersonInfo() : facePersonInfo;
    }

    public File getFaceFile() {
        return faceFile;
    }

    public void setFaceFile(File faceFile) {
        this.faceFile = faceFile;
    }

    public ImageIcon getFaceImage() {
        return faceImage;
    }

    public void setFaceImage(ImageIcon faceImage) {
        this.faceImage = faceImage;
    }

    public FacePersonInfo getFacePersonInfo() {
        return facePersonInfo;
    }

    public void setFacePersonInfo(FacePersonInfo facePersonInfo) {
        this.facePersonInfo = facePersonInfo;
    }
}
